#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"

void SeqListInit(SLT* ps)
{
	assert(ps);
	ps->capacity = 4;
	SLTDataType* ptr = (SLTDataType*)malloc(sizeof(SLTDataType)*ps->capacity);
	if (ptr == NULL)
	{
		perror("malloc fail");
		return;
	}
	ps->data = ptr;
	ps->size = 0;
}

void SLTDestroy(SLT* ps)
{
	assert(ps);
	free(ps->data);
	ps->data = NULL;
	ps->capacity = ps->size = 0;
}

void SLTCheckCapacity(SLT* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		SLTDataType* ptr = (SLTDataType*)realloc(ps->data,sizeof(SLTDataType) * (ps->capacity) * 2);
		if (ptr == NULL)
		{
			perror("realloc fail");
			return;
		}
		else
		{
			ps->data = ptr;
			ptr = NULL;
			ps->capacity *= 2;
		}
	}
}

void SLTPrint(SLT* ps)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ",ps->data[i]);
	}
	printf("\n");
}

void SLTPushBack(SLT* ps, SLTDataType x)
{
	//assert(ps);
	//SLTCheckCapacity(ps);
	//ps->data[ps->size] = x;
	//ps->size++;
	SLTInsert(ps, ps->size, x);
}

void SLTPopBack(SLT* ps)
{
	//assert(ps);
	//assert(ps->size > 0);
	//ps->size--;

	SLTErase(ps, ps->size - 1);
}

void SLTPushFront(SLT* ps, SLTDataType x)
{
	//assert(ps);
	//SLTCheckCapacity(ps);
	//int end = ps->size;
	//int begin = 0;
	//while (begin < end)
	//{
	//	ps->data[end] = ps->data[end - 1];
	//	end--;
	//}

	//ps->data[0] = x;
	//ps->size++;
	SLTInsert(ps, 0, x);
}

void SLTPopFront(SLT* ps)
{
	//assert(ps);
	//assert(ps->size > 0);
	//int begin = 0;
	//while (begin < ps->size)
	//{
	//	ps->data[begin] = ps->data[begin + 1];
	//	begin++;
	//}

	//ps->size--;
	SLTErase(ps, 0);
}

int SLTFind(SLT* ps, SLTDataType x)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SLTInsert(SLT* ps, size_t pos, SLTDataType x)
{
	assert(ps);
	SLTCheckCapacity(ps);
	int end = ps->size;
	while (pos < end)
	{
		ps->data[end] = ps->data[end - 1];
		end--;
	}

	ps->data[pos] = x;
	ps->size++;
}

void SLTErase(SLT* ps, size_t pos)
{
	assert(ps);
	assert(ps->size > 0);
	size_t end = ps->size-1;
	size_t begin = pos;
	while (begin < end)
	{
		ps->data[begin] = ps->data[begin+1];
		begin++;
	}

	ps->size--;
}